import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter App',
      theme: ThemeData(primarySwatch: Colors.red),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final GlobalKey _globalKey = GlobalKey();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Flutter App')),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 1.获取子widget属性, 并操作子widget的属性
          var boxState = _globalKey.currentState as _BoxState;
          boxState.setState(() {
            boxState._count++;
          });
          // 调用子组件方法
          boxState.run('父组件调用子组件方法');

          // 2 获取子widget (了解)
          var boxWidget = _globalKey.currentWidget as Box;
          print(
            boxWidget.color,
          ); //  MaterialColor(primary value: Color(0xfff44336))

          // 3 获取子widget 渲染熟悉 (了解)
          var renderBox =
              _globalKey.currentContext!.findRenderObject() as RenderBox;
          print(renderBox.size); // Size(100.0, 100.0)
        },
        child: const Icon(Icons.refresh),
      ),
      body: Center(
        child: Box(key: _globalKey, color: Colors.yellowAccent),
      ),
    );
  }
}

class Box extends StatefulWidget {
  final Color color;
  const Box({super.key, required this.color});

  @override
  State<Box> createState() => _BoxState();
}

class _BoxState extends State<Box> {
  int _count = 0;

  void run(value) {
    print('我是父组件传过来的值$value');
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 100,
      height: 100,
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: WidgetStateProperty.all(widget.color),
        ),
        onPressed: () {
          setState(() {
            _count++;
          });
        },
        child: Text('$_count', style: Theme.of(context).textTheme.displayLarge),
      ),
    );
  }
}
